import { isRelogin } from '@/config/axios/service'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { useTitle } from '@/hooks/web/useTitle'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getAccessToken } from '@/utils/auth'
import type { RouteRecordRaw } from 'vue-router'
import router from './router'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()
// 路由不重定向白名单
const whiteList = [
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee',
  '/pageH5',
  '/mp_official'
]

// 路由加载前
// router.beforeEach(async (to, from, next) => {
//   start()
//   loadStart()
//   if (getAccessToken()) {
//     if (to.path === '/login') {
//       next({ path: '/' })
//     } else {
//       // 获取所有字典
//       const dictStore = useDictStoreWithOut()
//       const userStore = useUserStoreWithOut()
//       const permissionStore = usePermissionStoreWithOut()
//       if (!dictStore.getIsSetDict) {
//         await dictStore.setDictMap()
//       }
//       if (!userStore.getIsSetUser) {
//         isRelogin.show = true
//         await userStore.setUserInfoAction()
//         isRelogin.show = false
//         // 后端过滤菜单
//         await permissionStore.generateRoutes()
//         permissionStore.getAddRouters.forEach((route) => {
//           router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
//         })
//         const redirectPath = from.query.redirect || to.path
//         const redirect = decodeURIComponent(redirectPath as string)
//         const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
//         next(nextData)
//       } else {
//         // 根据路由，获取模块前缀，然后对比userInfo.modules 判断是否拥有此模块
//         // 有 ->next()
//         // 无 ->next("${module}/noPermission")
//         // 因为CRM、ERP系统、企业搜索、呼叫中心都是免费使用的，
//         // 收费的是 机器人外呼、客户系统、广告系统、AI助手系统、
//         const blackList = ['crm', 'ent', 'call', 'erp', 'robot', 'service', 'ad', 'ai']
//         const path = to.path
//         // /404/111
//         const p2 = path.substring(1, path.length - 1)
//         // 404/111
//         const moduleName = p2.substring(0, p2.indexOf('/'))

//         if (path == `/${moduleName}/noPermission`) {
//           next()
//         }
//         if (blackList.includes(moduleName)) {
//           // 404
//           // 1. 如果访问的是付费才能开通的模块，就去判断权限
//           // 2. 如果该用户拥有此模块，就next() 通过
//           if (userStore.modules && userStore.modules.includes(moduleName)) {
//             next()
//           } else {
//             // 进入到此模块的 noPermission 路由；
//             next({ path: `/${moduleName}/noPermission` })
//           }
//         } else {
//           next()
//         }
//       }
//     }
//   } else {
//     if (whiteList.indexOf(to.path) !== -1) {
//       next()
//     } else {
//       next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
//     }
//   }
// })
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()

  if (getAccessToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      return
    }

    const dictStore = useDictStoreWithOut()
    const userStore = useUserStoreWithOut()
    const permissionStore = usePermissionStoreWithOut()

    // 确保字典数据已加载
    if (!dictStore.getIsSetDict) {
      await dictStore.setDictMap().catch(() => {
        console.error('加载字典数据失败')
      })
    }

    if (!userStore.getIsSetUser) {
      try {
        isRelogin.show = true
        await userStore.setUserInfoAction()
        isRelogin.show = false

        // 后端过滤菜单
        await permissionStore.generateRoutes()
        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw)
        })

        const redirectPath = from.query.redirect || to.path
        const redirect = decodeURIComponent(redirectPath as string)
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
        next(nextData)
        return
      } catch (e) {
        console.error('初始化用户数据失败:', e)
        next('/login') // 失败时跳转登录页
        return
      }
    }

    // 权限检查逻辑（完全保持原有代码）
    const blackList = ['crm', 'ent', 'call', 'erp', 'robot', 'service', 'ad', 'ai']
    const path = to.path
    const p2 = path.substring(1, path.length - 1)
    const moduleName = p2.substring(0, p2.indexOf('/'))

    if (path == `/${moduleName}/noPermission`) {
      next()
      return
    }

    if (blackList.includes(moduleName)) {
      if (userStore.modules && userStore.modules.includes(moduleName)) {
        next()
      } else {
        next({ path: `/${moduleName}/noPermission` })
      }
    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})
// 确保进度条和加载状态会被关闭
router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done()
  loadDone()
})
